package com.softer.chengxin.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 获取工作日日期
 *
 * @author Gong Zhiyang
 * @date 2018/9/29
 */
public class GetWorkDay {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * //获取公示截止日期
     *
     * @param list 节日结合(需要手动添加)
     * @param num  这个值就是业务需要的n个工作日
     * @return 日期
     * @throws ParseException
     */
    public static Date getExpiryDate(List<String> list, int num) throws ParseException {
        //Mon Aug 27 00:09:29 CST 2018
        Date today = new Date();
        Date tomorrow = null;
        int delay = 1;
        while (delay <= num) {
            tomorrow = getTomorrow(today);
            //当前日期+1即tomorrow,判断是否是节假日,同时要判断是否是周末,都不是则将scheduleActiveDate日期+1,直到循环num次即可
            if (!isWeekend(sdf.format(tomorrow)) && !isHoliday(sdf.format(tomorrow), list)) {
                delay++;
            }
            today = tomorrow;
        }
        System.out.println("10个工作日后,即计划激活日期为::" + sdf.format(today));
        return today;
    }

    /**
     * 获取明天的日期
     *
     * @param date
     * @return
     */
    public static Date getTomorrow(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);
        date = calendar.getTime();
        return date;
    }

    /**
     * 判断是否是weekend
     *
     * @param sdate 日期
     * @return true/false
     * @throws ParseException
     */
    public static boolean isWeekend(String sdate) throws ParseException {
        Date date = sdf.parse(sdate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 判断是否是holiday
     *
     * @param sdate 日期
     * @param list  节日集合
     * @return true/false
     * @throws ParseException
     */
    public static boolean isHoliday(String sdate, List<String> list) throws ParseException {
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (sdate.equals(list.get(i))) {
                    return true;
                }
            }
        }
        return false;
    }
}
